#include "bdd.h"

racine *root_head;
session **sess_tab;
uint sess_top;
char *bdd_path;
uint td_err;
char *tdversion;


subbase *add_subbase (subbase * par, subbase * head, char *id, byte c_s)
{
	uint len;
	subbase *n;
	
	n = malloc (sizeof (subbase));
	len = strlen (id);
	n->ident = malloc (len + 1);
	strcpy (n->ident, id);
	if (c_s == NO_CASE_SENS)
		low_string (n->ident);
    
	n->hash = chksum_crc32 (n->ident, len);
	n->parent = par;
	n->rows = NULL;
	n->last_row = NULL;
	n->der_enfant = NULL;
	n->enfant = NULL;
	
	n->prev = par->der_enfant;
	n->next = NULL;
	
	if (par->der_enfant)
	{
		/*printf ("ajout subbase %s derriere %s (parent %s)\n", id, par->der_enfant->ident, par->ident);*/
		par->der_enfant->next = n;
	}
	else
	{
		/*printf ("ajout subbase %s unique (parent %s)\n", id, par->ident);	*/
		par->enfant = n;
	}
	
	par->der_enfant = n;
	
	return (par->enfant);
}


racine *
add_base (racine * head, char *id, byte c_s)
{
  uint len;
  racine *n = malloc (sizeof (racine));
  n->base = malloc (sizeof (subbase));
  len = strlen (id);
  n->base->ident = malloc (len + 1);
  strcpy (n->base->ident, id);
  n->case_flag = c_s;
  if (c_s == NO_CASE_SENS)
    low_string (n->base->ident);
  n->base->hash = chksum_crc32 (n->base->ident, len);

  n->base->parent = NULL;
  n->base->enfant = NULL;
  n->base->der_enfant = NULL;
  n->base->next = NULL;
  n->base->prev = NULL;
  n->base->rows = NULL;
  n->base->last_row = NULL;
  

  n->next = head;
  n->prev = NULL;
  if (head)
    head->prev = n;

  return (n);
}


row *add_row (subbase *parent, char *id, char *va, byte c_s)
{
	uint len;
	row *n;
	
	n = malloc (sizeof (row));
	len = strlen (id);
	n->ident = malloc (len + 1);
	n->val = malloc (strlen (va) + 1);
	strcpy (n->ident, id);
	
	if (c_s == NO_CASE_SENS)
		low_string (n->ident);
	strcpy (n->val, va);
	n->hash = chksum_crc32 (n->ident, len);
	
	n->prev = parent->last_row;
	n->next = NULL;
	if (parent->last_row)
	{
		/*printf ("ajout row %s derriere %s (parent %s)\n", id, parent->last_row->ident, parent->ident);*/
		parent->last_row->next = n;
	}
	else
	{
		/*printf ("ajout row %s unique (parent %s)\n", id, parent->ident);*/
		parent->rows = n;
	}
	
	parent->last_row = n;
	
	return (parent->rows);
}


uint
add_session ()
{
  uint a;
  for (a = 1; a < sess_top; a++)
    if (!sess_tab[a])
      {
	*(sess_tab + a) = malloc (sizeof (session));
	sess_tab[a]->subptr = NULL;
	sess_tab[a]->rowptr = NULL;
	sess_tab[a]->baseptr = NULL;
	sess_tab[a]->rootptr = NULL;
	return a;
      }

  if (!sess_top)
    sess_tab = malloc (sizeof (session *));

  else
    sess_tab = realloc (sess_tab, (sess_top + 1) * sizeof (session *));

  *(sess_tab + sess_top) = malloc (sizeof (session));

  sess_tab[sess_top]->subptr = NULL;
  sess_tab[sess_top]->rowptr = NULL;
  sess_tab[sess_top]->baseptr = NULL;
  sess_tab[sess_top]->rootptr = NULL;

  sess_top++;
  return (sess_top - 1);
}
